# Create your views here.
from django.template import RequestContext
from django.shortcuts import render_to_response
from thesocialstockmarket.users.forms import *
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import  PasswordChangeForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from thesocialstockmarket.users.models import *
from thesocialstockmarket.personalstock.models import *
from django.conf.urls.defaults import *



def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            username = request.POST['username']
            password = request.POST['password1']
            user = authenticate(username=username, password = password)
            login(request,user)
            useraccount = UserAccount(user = request.user)
            useraccount.save()
        
            return HttpResponseRedirect("/users/profile")
    else:
        form = UserCreationForm()
    return render_to_response('users/register.html', {'form': form})


@login_required()
def profile(request):
    u = User.objects.get(username = request.user.username)
    useraccount = u.related_user
    transaction = Transactions.objects.filter(user=u)
    if request.method == 'POST': 
        form = UserImageForm(request.POST,request.FILES,instance = useraccount)
        if form.is_valid():
            form.save()
    else:
        form = UserImageForm(instance = useraccount)
    return render_to_response('users/profile.html', {'user': u,
                                                     'useraccount': useraccount,
                                                     'transaction' : transaction,
                                                     'form':form,
                                                     })



def stock(request):
    stocks = Stock.objects.all() 
    return render_to_response('users/stock.html', 
                              {'stocks': stocks ,
                               'user':request.user,
                               })


def news(request):
    news = News.objects.order_by('date')[:20]
    return render_to_response('users/latestnews.html', 
                              {'news': news,
                               'user':request.user,})



def show_latestnews_content(request, id):
    try:
        u = User.objects.get(username= request.user.username)
    except User.DoesNotExist:
        u =  None
    try:
        newsdetail = News.objects.get(id = id)
    except News.DoesNotExist:
        raise Http404
    try:
        stock = Stock.objects.get(id = newsdetail.stock_id)
    except Stock.DoesNotExist:
        raise Http404
    try:
        has_rated = NewsRating.objects.get(news = newsdetail, user = u)
        form =  None
    except:
        if request.method == 'POST': 
            form = NewsRatingForm(request.POST)
            if form.is_valid():
                rating = form.save(commit = False)
                rating.user = request.user
                try :
                    n = News.objects.get(pk = id)
                except  News.DoesNotExist :
                    raise Http404
                rating.news = n
                rating.save()
        else:
            form = NewsRatingForm()
        try:
            has_rated = NewsRating.objects.get(news = newsdetail, user = u)
        except NewsRating.DoesNotExist:
            has_rated =  None
    return render_to_response('users/news_rating.html',
                              {'user': u,
                               'newsdetail':newsdetail,
                               'has_rated': has_rated,
                               'form': form,
                               'stock':stock})
    




def show_news(request, stock_name):
    try:
        stock = Stock.objects.get(stock_name = stock_name)
    except Stock.DoesNotExist:
        raise Http404
    news = News.objects.filter(stock = stock ).order_by('date')[:20]


    return render_to_response('users/news.html',
            {
             'news': news,                               
             'user': request.user,
             's': stock,
#             'form': form,
#            'rated': rated,
             })


def show_news_content(request, id, stock_name):
    try:
        u = User.objects.get(username= request.user.username)
    except User.DoesNotExist:
        u =  None
    try:
        stock = Stock.objects.get(stock_name = stock_name)
    except Stock.DoesNotExist:
        raise Http404
    try:
        newsdetail = News.objects.get(id = id)
    except News.DoesNotExist:
        raise Http404
    
    try:
        has_rated = NewsRating.objects.get(news = newsdetail, user = u)
        form =  None
    except:
        if request.method == 'POST': 
            form = NewsRatingForm(request.POST)
            if form.is_valid():
                rating = form.save(commit = False)
                rating.user = request.user
                try :
                    n = News.objects.get(pk = id)
                except  News.DoesNotExist :
                    raise Http404
                rating.news = n
                rating.save()
        else:
            form = NewsRatingForm()
        try:
            has_rated = NewsRating.objects.get(news = newsdetail, user = u)
        except NewsRating.DoesNotExist:
            has_rated =  None
    return render_to_response('users/news_rating.html',
                              {'user': u,
                               'newsdetail':newsdetail,
                               'has_rated': has_rated,
                               'form': form,
                               'stock':stock})
    
    
    
    
def newsrating(request):
    newsrating = NewsRating.objects.all()
    return render_to_response('users/news_rating.html',
                               {'newsrating': newsrating,
                                'user':request.user})



def introduction(request):
    return render_to_response('users/introduction.html', {'user': request.user})

def show_members(request):
    alluser = User.objects.exclude(username = request.user.username)
    friendship = FriendShip.objects.all()

    return render_to_response('users/members.html',
            {'alluser': alluser,
             'user': request.user,
             'friendship': friendship,
             })




@login_required
def show_friends(request):
    u = User.objects.get(username = request.user.username)
    request = FriendShip.objects.filter(to_friend = u )
    try:
        friend = FriendShip.objects.filter(from_friend = u)
    except FriendShip.DoesNotExist:
        friend =  None
    return render_to_response('users/friend.html',
            {'request':request,
             'friend': friend,
             'user':u
             })
    
    
    
@login_required
def show_fri_details(request,from_friend):
    friend = User.objects.get(username = from_friend)
    try:
       perstock = PerStock.objects.filter(user = friend)
    except:
        return HttpResponseRedirect('fri_nostock' )
    
    return render_to_response('users/fri_details.html',
            {'friend':friend,
              'perstock':perstock,
              'stock':stock 
             })


@login_required
def fri_nostock(request,from_friend):
    friend = User.objects.get(username = from_friend)
    
    return render_to_response('users/fri_nostock.html',
                              {'friend':friend,
             }
            )
    

    
@login_required
def fri_request(request,to_friend):
    try:
        user2 = User.objects.get(username = to_friend)
        try :
            friendship = FriendShip.objects.get(from_friend = user2 , to_friend = request.user , confirmed = True)
            return HttpResponseRedirect('/users/fri_exist/')
        except FriendShip.DoesNotExist :
            request = FriendShip(from_friend = request.user , to_friend = user2 , confirmed = False)
            request.save()
            
    except :
        return HttpResponseRedirect("/users/fri_requestfail")
    return render_to_response('users/fri_request.html', 
                              {'request': request,
                             })
    
    
    
@login_required
def fri_exist(request):
   
    return render_to_response('users/fri_exist.html')




@login_required
def fri_requestfail(request):
   
    return render_to_response('users/fri_requestfail.html')



@login_required
def fri_confirm(request,from_friend):
    user1 = User.objects.get(username = from_friend)
    try :
        friendship = FriendShip.objects.get(from_friend = user1 , to_friend = request.user , confirmed = False)
    except FriendShip.DoesNotExist :
        return HttpResponseRedirect('/users/profile/')
    friendship.confirmed = True 
    friendship.save()
    return render_to_response('users/fri_confirm.html', {'friendship': friendship})



@login_required
def fri_delete(request,from_friend):
    user1 = User.objects.get(username = from_friend)
    try:
        friendship = FriendShip.objects.get(from_friend = user1, to_friend = request.user)
    except:
        friendship = FriendShip.objects.get(to_friend = user1, from_friend = request.user)
    friendship.delete()
    return render_to_response('users/fri_delete.html', 
                              {'friendship': friendship})
    

@login_required
def fri_reject(request,from_friend):
    user1 = User.objects.get(username = from_friend)
    friendship = FriendShip.objects.get(from_friend = user1 , to_friend = request.user , confirmed = False)
    friendship.delete()
    return render_to_response('users/fri_reject.html', {'friendship': friendship})

@login_required
def changepassword(request):
    if request.method == 'POST':
        userform = PasswordChangeForm(request.user,request.POST)
        if userform.is_valid():
            userform.save() 
            return HttpResponseRedirect("/users/profile")
    else:
        userform = PasswordChangeForm(request.user)
    return render_to_response('users/changepassword.html',
                              {'user': request.user,
                               'userform':userform})


